<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px" size="small">
      <el-form-item label="房屋名称" prop="houseId">
        <el-input v-model="selectedHouseName" placeholder="点击选择房屋" readonly>
          <el-button slot="append" icon="el-icon-search" @click="showHouseSelect"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="排查结论" prop="conclusion">
        <el-select v-model="queryParams.conclusion" placeholder="请选择排查结论" size="small">
            <el-option clearable v-for="item in dict.type.safety_danger_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['house:safety:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="safetyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="房屋名称" align="center" prop="houseName" :show-overflow-tooltip="true" />
      <el-table-column label="建筑场地安全隐患" align="center" prop="siteDanger">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.safety_site_danger_type" :value="scope.row.siteDanger"/>
        </template>
      </el-table-column>
      <el-table-column label="地基基础安全隐患" align="center" prop="foundationDanger">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.safety_danger_type" :value="scope.row.foundationDanger"/>
        </template>
      </el-table-column>
      <el-table-column label="上部结构安全隐患" align="center" prop="structureDanger">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.safety_danger_type" :value="scope.row.structureDanger"/>
        </template>
      </el-table-column>
      <el-table-column label="排查结论" align="center" prop="conclusion">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.safety_danger_type" :value="scope.row.conclusion"/>
        </template>
      </el-table-column>
      <el-table-column label="排查日期" align="center" prop="checkDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:safety:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['house:safety:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 房屋选择弹窗 -->
    <el-dialog :title="'选择房屋'" :visible.sync="houseSelectVisible" width="1000px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :model="houseQueryParams" ref="houseQueryForm" :inline="true" label-width="68px">
        <el-form-item label="项目名称" prop="projectId">
          <el-select 
            v-model="houseQueryParams.projectId" 
            placeholder="请选择项目" 
            clearable 
            filterable 
            :filter-method="filterHouseProjects"
            @change="handleHouseProjectChange"
            size="small"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋名称" prop="houseName">
          <el-input
            v-model="houseQueryParams.houseName"
            placeholder="请输入房屋名称"
            clearable
            size="small"
            @keyup.enter.native="handleHouseQuery"
          />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select 
            v-model="houseQueryParams.province" 
            placeholder="请选择省份" 
            clearable 
            size="small"
            @change="handleProvinceChange"
          >
            <el-option
              v-for="item in provinceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select 
            v-model="houseQueryParams.city" 
            placeholder="请选择城市" 
            clearable 
            size="small"
            @change="handleCityChange"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="district">
          <el-select 
            v-model="houseQueryParams.district" 
            placeholder="请选择区域" 
            clearable 
            size="small"
          >
            <el-option
              v-for="item in districtOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleHouseQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetHouseQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 房屋列表 -->
      <el-table
        v-loading="houseLoading"
        :data="houseList"
        @row-click="handleSelectHouse"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="房屋名称" prop="houseName" />
        <el-table-column label="房屋编号" prop="houseCode" />
        <el-table-column label="地址" prop="address" :show-overflow-tooltip="true"/>
        <el-table-column label="建筑面积" prop="buildingArea" align="center" />
        <el-table-column label="风险等级" align="center" prop="riskLevel">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.house_risk_level" :value="scope.row.riskLevel"/>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="houseTotal>0"
        :total="houseTotal"
        :page.sync="houseQueryParams.pageNum"
        :limit.sync="houseQueryParams.pageSize"
        @pagination="getHouseList"
      />
    </el-dialog>

    <!-- 添加表单组件 -->
    <safety-form ref="safetyForm" />
  </div>
</template>

<script>
import { listSafety, getSafety, delSafety, addSafety, updateSafety } from "@/api/house/safety";
import { listHouse } from "@/api/house/house";
import { listProvinceOptions } from "@/api/house/province";
import { listCityOptions } from "@/api/house/city";
import { listDistrictOptions } from "@/api/house/district";
import SafetyForm from "./form";
import { listProjects } from "@/api/house/project";

export default {
  name: "Safety",
  dicts: ['safety_site_danger_type', 'safety_danger_type', 'house_risk_level'],
  components: {
    SafetyForm
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房屋安全排查表格数据
      safetyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        houseId: null,
        siteDanger: null,
        foundationDanger: null,
        structureDanger: null,
        conclusion: null,
        checkDate: null
      },
      // 房屋选择相关数据
      houseSelectVisible: false,
      houseLoading: false,
      houseList: [],
      houseTotal: 0,
      houseQueryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        houseName: null,
        province: null,
        city: null,
        district: null
      },
      // 省市区数据
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      // 选中的房屋名称
      selectedHouseName: '',
      // 房屋选择来源标识（add: 新增按钮, search: 查询条件）
      selectSource: '',
      // 项目选项数据
      projectOptions: []
    };
  },
  created() {
    this.getList();
    this.loadProvinceOptions();
    this.loadProjectOptions();
  },
  methods: {
    /** 加载项目列表数据 */
    loadProjectOptions() {
      listProjects().then(response => {
        this.projectOptions = response.rows;
      });
    },
    /** 查询房屋安全排查列表 */
    getList() {
      this.loading = true;
      listSafety(this.queryParams).then(response => {
        this.safetyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.selectedHouseName = '';
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.selectSource = 'add';
      this.houseSelectVisible = true;
      this.getHouseList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.safetyForm.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除安全排查编号为"' + ids + '"的数据项？').then(() => {
        return delSafety(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // TODO: 实现导出功能
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查询房屋列表 */
    getHouseList() {
      this.houseLoading = true;
      listHouse(this.houseQueryParams).then(response => {
        this.houseList = response.rows;
        this.houseTotal = response.total;
        this.houseLoading = false;
      });
    },
    /** 显示选择房屋弹窗 */
    showHouseSelect() {
      this.selectSource = 'search';
      this.houseSelectVisible = true;
      this.getHouseList();
    },
    /** 选择房屋 */
    handleSelectHouse(row) {
      if (this.selectSource === 'add') {
        this.houseSelectVisible = false;
        this.$refs.safetyForm.handleAdd(row);
      } else {
        this.selectedHouseName = row.houseName;
        this.queryParams.houseId = row.houseId;
        this.houseSelectVisible = false;
        this.handleQuery();
      }
    },
    /** 搜索房屋按钮操作 */
    handleHouseQuery() {
      this.houseQueryParams.pageNum = 1;
      this.getHouseList();
    },
    /** 重置房屋查询操作 */
    resetHouseQuery() {
      this.resetForm("houseQueryForm");
      this.houseQueryParams.projectId = null;
      this.houseQueryParams.province = null;
      this.houseQueryParams.city = null;
      this.houseQueryParams.district = null;
      this.cityOptions = [];
      this.districtOptions = [];
      this.handleHouseQuery();
    },
    /** 加载省份数据 */
    loadProvinceOptions() {
      listProvinceOptions().then(response => {
        this.provinceOptions = response.rows.map(item => ({
          value: item.provinceCode,
          label: item.provinceName
        }));
      });
    },
    /** 加载城市数据 */
    loadCityOptions(provinceCode) {
      listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.cityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },
    /** 加载区域数据 */
    loadDistrictOptions(cityCode) {
      listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.districtOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },
    /** 省份选择改变事件 */
    handleProvinceChange(value) {
      if (value) {
        this.loadCityOptions(value);
        this.houseQueryParams.city = null;
        this.houseQueryParams.district = null;
        this.districtOptions = [];
      } else {
        this.cityOptions = [];
        this.districtOptions = [];
        this.houseQueryParams.city = null;
        this.houseQueryParams.district = null;
      }
    },
    /** 城市选择改变事件 */
    handleCityChange(value) {
      if (value) {
        this.loadDistrictOptions(value);
        this.houseQueryParams.district = null;
      } else {
        this.districtOptions = [];
        this.houseQueryParams.district = null;
      }
    },
    /** 项目选择框筛选方法（房屋选择弹窗中使用） */
    filterHouseProjects(query) {
      if (query) {
        const search = query.toLowerCase();
        return this.projectOptions.filter(item => 
          item.projectName.toLowerCase().includes(search)
        );
      } else {
        return this.projectOptions;
      }
    },
    /** 项目选择变化处理（房屋选择弹窗中使用） */
    handleHouseProjectChange(projectId) {
      this.houseQueryParams.projectId = projectId;
      this.handleHouseQuery();
    },
  }
};
</script>

<style scoped>
.el-table {
  margin-top: 15px;
}

.el-table .fixed-width .el-button--mini {
  padding-left: 0;
  padding-right: 0;
  width: 60px;
}

.mb8 {
  margin-bottom: 8px;
}

.el-form-item {
  margin-bottom: 8px;
}

.el-form-item--small.el-form-item {
  margin-bottom: 8px;
}
</style> 